package com.onlineshopping.interceptor;

import com.onlineshopping.entity.Result;
import com.onlineshopping.entity.User;
import com.onlineshopping.enums.ReturnCode;
import com.onlineshopping.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(JwtInterceptor.class);

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    /**
     * 在请求处理之前进行调用（Controller方法调用之前）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        // 从请求头获取token
        String authHeader = request.getHeader(this.tokenHeader);
        // System.out.println(tokenHeader);
        // System.out.println(authHeader);
        if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
            // 解析token
            String authToken = authHeader.substring(this.tokenHead.length());
            // 获取当前登录的用户信息
            String username = JwtTokenUtil.getUserNameFromToken(authToken);
            if (username == null) {
                // token过期或无效
                String json = new ObjectMapper().writeValueAsString(Result.error(ReturnCode.RC500.getCode(), "token过期或无效"));
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println(json);
                LOGGER.error("token过期或无效");
                return false;
            }
            //LOGGER.info("用户{}登录成功", username);
            // 当前用户
            User user = new User();
            user.setUsername(username);
            // 验证token
            if (JwtTokenUtil.validateToken(authToken, user)) {
                // 放行
                return true;
            }
        }
        // 未登录，返回错误信息
        String json = new ObjectMapper().writeValueAsString(Result.error(ReturnCode.RC500.getCode(), "未登录"));
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在整个请求结束之后被调用，也就是在 DispatcherServlet 渲染了对应的视图之后执行（主要是用于清理资源）
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}